package cn.livingCloud.controller.core;

import cn.livingCloud.dto.DeptFormDto;
import cn.livingCloud.dto.DeptListDto;
import cn.livingCloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * 部门控制器
 * Created by DingJie on 2016/5/26.
 */
@Controller
@RequestMapping("/admin/organization/dept")
public class DeptController {
    @Autowired
    private DeptService service;

    @RequestMapping("/list.htm")
    public String loadList(DeptListDto listDto, Model model) {
        service.loadDeptList(listDto);
        model.addAttribute("listDto", listDto);
        return "organization/dept/list";
    }

    @RequestMapping("/edit.htm")
    public String edit(String uuid, String parent_uuid, Model model) {
        DeptFormDto formDto = service.loadDeptFromDto(uuid, parent_uuid);
        model.addAttribute("formDto", formDto);
        return "organization/dept/edit";
    }

    @RequestMapping(value = "/edit.htm", method = RequestMethod.POST)
    public String edit(@ModelAttribute("formDto") @Valid DeptFormDto formDto, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "organization/dept/edit";
        }
        String parentUuid = service.edit(formDto);
        model.addAttribute("edit", "success");
        model.addAttribute("parent_uuid", parentUuid);
        return "redirect:/admin/organization/dept/list.htm";
    }

    //删除
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    public String delete(String uuid, String parent_uuid, Model model) {
        String parentUuid = service.delete(uuid, parent_uuid);
        model.addAttribute("parent_uuid", parentUuid);
        model.addAttribute("delete", "success");
        return "redirect:list.htm";
    }
}
